package com.wyzz.hr.bo.impl;

import com.wyzz.hr.base.Constants;
import com.wyzz.hr.base.FileOperate;
import com.wyzz.hr.bo.IClientBO;
import com.wyzz.hr.bo.IEmailsendBO;
import com.wyzz.hr.bo.IEmailtemplateBO;
import com.wyzz.hr.bo.IEmpHistOrgBo;
import com.wyzz.hr.bo.IEmployeeBo;
import com.wyzz.hr.bo.IPositionBo;
import com.wyzz.hr.bo.RoleBo;
import com.wyzz.hr.bo.UserBo;
import com.wyzz.hr.dao.IDepartmentDAO;
import com.wyzz.hr.dao.IEmployeeDAO;
import com.wyzz.hr.dao.IStatusDAO;
import com.wyzz.hr.pojo.Department;
import com.wyzz.hr.pojo.Emailsend;
import com.wyzz.hr.pojo.Emailtemplate;
import com.wyzz.hr.pojo.Employee;
import com.wyzz.hr.pojo.Emptransfer;
import com.wyzz.hr.pojo.Emptype;
import com.wyzz.hr.pojo.Location;
import com.wyzz.hr.pojo.Position;
import com.wyzz.hr.pojo.PositionBase;
import com.wyzz.hr.pojo.Role;
import com.wyzz.hr.pojo.Userinfo;
import com.wyzz.hr.report.action.support.EmpSumReport;
import com.wyzz.hr.spring.SpringBeanFactory;
import com.wyzz.hr.util.DateUtil;
import com.wyzz.hr.util.GenericValidator;
import com.wyzz.hr.util.Pager;
import com.wyzz.hr.util.StringUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.FetchMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

public class EmployeeBoImpl implements IEmployeeBo, Constants {

	public EmployeeBoImpl() {
		msgIsREG = "{0}\u5DF2\u7ECF\u662F\u6B63\u5F0F\u5458\u5DE5\uFF0C\u4E0D\u80FD\u518D\u6B21\u8F6C\u6B63\uFF01";
		// 已经是正式员工不能再次转正！
		msgPbNull = "\u65B0\u7EC4\u7EC7\u5355\u5143\u4E0D\u80FD\u4E3A\u7A7A!";
		// 新组织单元不能为空!
		msgPbNoChange = "{0}\u7684\u53D8\u52A8\u524D\u804C\u4F4D\u4E0E\u53D8\u52A8\u540E\u804C\u4F4D\u76F8\u540C\uFF0C\u4E0D\u80FD\u79FB\u52A8\uFF01";
		// 的变动前职位与变动后职位相同，不能移动！
	}

	public IEmployeeDAO getEmployeeDAO() {
		return employeeDAO;
	}

	public List getEmpStatus() {
		return statusDAO.getStatusByTable("employee");
	}

	public Employee loadEmpByDistinctNo(String empDistinctNo) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Employee.class);
		detachedCriteria.add(Restrictions.eq(Employee.PROP_EMP_DISTINCT_NO,
				empDistinctNo));
		List list = employeeDAO.findByCriteria(detachedCriteria);
		if (list.size() == 1)
			return (Employee) list.get(0);
		else
			return null;
	}

	public List exeHqlList(String hql, int page[]) {
		if (page.length == 0)
			return employeeDAO.exeHqlList(hql);
		int currPage = 1;
		if (page.length > 1)
			currPage = page[1];
		return employeeDAO.exeHqlList(hql, page[0], currPage);
	}

	public List exeHqlList(String hql, String fields[], String conditions[]) {
		return employeeDAO.exeHqlList(hql, fields, conditions);
	}

	public List findByCriteria(DetachedCriteria detachedCriteria) {
		return employeeDAO.findByCriteria(detachedCriteria);
	}

	public int findRowCountByCriteria(DetachedCriteria detachedCriteria) {
		return employeeDAO.findRowCountByCriteria(detachedCriteria);
	}

	public void saveOrupdate(Collection objs) {
		employeeDAO.saveOrupdate(objs);
	}

	public void setEmployeeDAO(IEmployeeDAO employeeDAO) {
		this.employeeDAO = employeeDAO;
	}

	public List deleteEmp(Employee emp) {
		List errors = checkEmp(emp, "delete");
		if (errors.size() < 1) {
			FileOperate.deleteFile("sys.user.image.path", emp.getEmpImage());
			if (StringUtils.isNotEmpty(emp.getEmpResume1()))
				FileOperate.deleteFile("sys.profile.file.path", emp
						.getEmpResume1());
			if (StringUtils.isNotEmpty(emp.getEmpResume2()))
				FileOperate.deleteFile("sys.profile.file.path", emp
						.getEmpResume2());
			String deleteHistoryEduHql = (new StringBuilder()).append(
					"delete from Emphistoryedu as ee where ee.employee.id='")
					.append(emp.getId()).append("'").toString();
			employeeDAO.updateHqlQuery(deleteHistoryEduHql);
			String deleteHistoryJobHql = (new StringBuilder()).append(
					"delete from Emphistoryjob as eh where eh.employee.id='")
					.append(emp.getId()).append("'").toString();
			employeeDAO.updateHqlQuery(deleteHistoryJobHql);
			String deleteHistoryTrainingHql = (new StringBuilder()).append(
					"delete from Emphistorytrain as et where et.employee.id='")
					.append(emp.getId()).append("'").toString();
			employeeDAO.updateHqlQuery(deleteHistoryTrainingHql);
			String deleteTransferHql = (new StringBuilder()).append(
					"delete from Emptransfer as e where e.employee.id='")
					.append(emp.getId()).append("'").toString();
			employeeDAO.updateHqlQuery(deleteTransferHql);
			String deleteEvalHql = (new StringBuilder()).append(
					"delete from Empeval as e where e.employeeByEeEmpNo.id='")
					.append(emp.getId()).append("'").toString();
			employeeDAO.updateHqlQuery(deleteEvalHql);
			String deleteRewardHql = (new StringBuilder()).append(
					"delete from Empreward as r where r.employee.id='").append(
					emp.getId()).append("'").toString();
			employeeDAO.updateHqlQuery(deleteRewardHql);
			String deleteQuitHql = (new StringBuilder()).append(
					"delete from Empquit as e where e.employee.id='").append(
					emp.getId()).append("'").toString();
			employeeDAO.updateHqlQuery(deleteQuitHql);
			String deleteUserHql = (new StringBuilder()).append(
					"delete from Userinfo as u where u.id='").append(
					emp.getId()).append("'").toString();
			employeeDAO.updateHqlQuery(deleteUserHql);
			String deleteEmpHistOrg = (new StringBuilder()).append(
					"delete from EmpHistOrg where ehoEmpNo.id='").append(
					emp.getId()).append("'").toString();
			employeeDAO.updateHqlQuery(deleteEmpHistOrg);
			String deleteEmpPosition = (new StringBuilder())
					.append(
							"update Position set positionEmpNo.id=null where positionEmpNo.id='")
					.append(emp.getId()).append("'").toString();
			employeeDAO.updateHqlQuery(deleteEmpPosition);
			String deleteEmpSyncHql = (new StringBuilder()).append(
					"delete from AttdSyncRecord where asrEmp.id='").append(
					emp.getId()).append("'").toString();
			employeeDAO.updateHqlQuery(deleteEmpSyncHql);
			String deleteEmpHql = (new StringBuilder()).append(
					"delete Employee as e where e.id='").append(emp.getId())
					.append("'").toString();
			employeeDAO.updateHqlQuery(deleteEmpHql);
		}
		return errors;
	}

	public List getObjects(Class clas, String fetch[]) {
		List result = employeeDAO.getObjects(clas, fetch);
		return result;
	}

	private List checkEmp(Employee emp, String perat) {
		List errors = new ArrayList();
		if (!perat.equalsIgnoreCase("delete")) {
			if (emp.getEmpBirthDate() != null
					&& emp.getEmpBirthDate().getTime() > (new Date()).getTime() - 0x5265c00L)
				errors
						.add("\u51FA\u751F\u65E5\u671F\u5FC5\u987B\u5C0F\u4E8E\u4ECA\u5929\uFF01");
			if (emp.getEmpBirthDate() != null
					&& emp.getEmpWorkDate() != null
					&& emp.getEmpBirthDate().compareTo(emp.getEmpWorkDate()) > 0)
				errors
						.add("\u51FA\u751F\u65E5\u671F\u4E0D\u80FD\u665A\u4E8E\u53C2\u52A0\u5DE5\u4F5C\u65E5\u671F\uFF01");
			if (emp.getEmpJoinDate() != null && emp.getEmpWorkDate() != null
					&& emp.getEmpJoinDate().compareTo(emp.getEmpWorkDate()) < 0)
				errors
						.add("\u53C2\u52A0\u5DE5\u4F5C\u65E5\u671F\u4E0D\u80FD\u665A\u4E8E\u5165\u804C\u65E5\u671F\uFF01");
			if (emp.getEmpConfirmDate() != null
					&& emp.getEmpJoinDate() != null
					&& emp.getEmpConfirmDate().compareTo(emp.getEmpJoinDate()) < 0)
				errors
						.add("\u5165\u804C\u65E5\u671F\u4E0D\u80FD\u665A\u4E8E\u8F6C\u6B63\u65E5\u671F\uFF01");
			if (emp.getEmpWorkPhone() != null
					&& emp.getEmpWorkPhone().trim().length() > 0
					&& !GenericValidator.isPhone(emp.getEmpWorkPhone()))
				errors
						.add("\u5DE5\u4F5C\u7535\u8BDD\u683C\u5F0F\u9519\u8BEF\uFF01\u53EA\u5141\u8BB8\u6570\u5B57\u3001\"-\"\uFF01");
			if (emp.getEmpHomePhone() != null
					&& emp.getEmpHomePhone().trim().length() > 0
					&& !GenericValidator.isPhone(emp.getEmpHomePhone()))
				errors
						.add("\u5BB6\u5EAD\u7535\u8BDD\u683C\u5F0F\u9519\u8BEF\uFF01\u53EA\u5141\u8BB8\u6570\u5B57\u3001\"-\"\u3001\"_\"\uFF01");
		}
		if (perat.equals("update")) {
			String hql = (new StringBuilder()).append(
					"from Employee where empDistinctNo = '").append(
					emp.getEmpDistinctNo().trim()).append("'").toString();
			List emps = employeeDAO.exeHqlList(hql);
			for (int i = 0; emps != null && i < emps.size(); i++) {
				Employee tempEmp = (Employee) emps.get(i);
				if (!tempEmp.getId().equals(emp.getId()))
					errors.add((new StringBuilder()).append(
							"\u5458\u5DE5\u7F16\u53F7").append(
							emp.getEmpDistinctNo().trim()).append(
							"\u5DF2\u7ECF\u5B58\u5728\uFF01").toString());
			}

			if (StringUtils.isNotEmpty(emp.getEmpShiftNo())) {
				String sql = (new StringBuilder()).append(
						"from Employee where empShiftNo = '").append(
						emp.getEmpShiftNo().trim()).append(
						"' and empStatus = 1").toString();
				List list = employeeDAO.exeHqlList(sql);
				for (int i = 0; list != null && i < list.size(); i++) {
					Employee tempEmp = (Employee) list.get(i);
					if (!tempEmp.getId().equals(emp.getId()))
						errors.add((new StringBuilder()).append(
								"\u8003\u52E4\u5361\u53F7").append(
								emp.getEmpShiftNo().trim()).append(
								"\u5DF2\u7ECF\u5B58\u5728\uFF01").toString());
				}

			}
			if (StringUtils.isNotEmpty(emp.getEmpIdentificationNo())
					&& emp.getEmpIdentificationType().intValue() == 0) {
				String sql = (new StringBuilder()).append(
						"from Employee where empIdentificationNo = '").append(
						emp.getEmpIdentificationNo().trim()).append(
						"' and empIdentificationType=0").toString();
				List list = employeeDAO.exeHqlList(sql);
				int i = 0;
				do {
					if (list == null || i >= list.size())
						break;
					Employee tempEmp = (Employee) list.get(i);
					if (!tempEmp.getId().equals(emp.getId())) {
						errors.add((new StringBuilder()).append(
								"\u8EAB\u4EFD\u8BC1\u53F7").append(
								emp.getEmpIdentificationNo().trim()).append(
								"\u5DF2\u7ECF\u5B58\u5728\uFF01").toString());
						break;
					}
					i++;
				} while (true);
			}
			return errors;
		}
		if (perat.equals("create")) {
			String hql = (new StringBuilder()).append(
					"from Employee where empDistinctNo = '").append(
					emp.getEmpDistinctNo().trim()).append("'").toString();
			List emps = employeeDAO.exeHqlList(hql);
			if (emps != null && emps.size() > 0)
				errors.add((new StringBuilder()).append(
						"\u5458\u5DE5\u7F16\u53F7").append(
						emp.getEmpDistinctNo().trim()).append(
						"\u5DF2\u7ECF\u5B58\u5728\uFF01").toString());
			if (StringUtils.isNotEmpty(emp.getEmpShiftNo())) {
				String sql = (new StringBuilder()).append(
						"from Employee where empShiftNo = '").append(
						emp.getEmpShiftNo().trim()).append("'").toString();
				List list = employeeDAO.exeHqlList(sql);
				if (!list.isEmpty())
					errors.add((new StringBuilder()).append(
							"\u8003\u52E4\u5361\u53F7").append(
							emp.getEmpShiftNo().trim()).append(
							"\u5DF2\u7ECF\u5B58\u5728\uFF01").toString());
			}
			if (StringUtils.isNotEmpty(emp.getEmpIdentificationNo())
					&& emp.getEmpIdentificationType().intValue() == 0) {
				String sql = (new StringBuilder()).append(
						"from Employee where empIdentificationNo = '").append(
						emp.getEmpIdentificationNo().trim()).append(
						"' and empIdentificationType=0").toString();
				List list = employeeDAO.exeHqlList(sql);
				if (!list.isEmpty())
					errors.add((new StringBuilder()).append(
							"\u8EAB\u4EFD\u8BC1\u53F7").append(
							emp.getEmpIdentificationNo().trim()).append(
							"\u5DF2\u7ECF\u5B58\u5728\uFF01").toString());
			}
			return errors;
		}
		if (perat.equals("delete")) {
			String info = "";
			if (checkRelate("Empcontract", "employee.id", emp.getId()))
				info = StringUtil.addConcatStr(info, "\u3001",
						new Object[] { "\u6709\u4EBA\u4E8B\u5408\u540C" });
			if (checkRelate("Empsalaryadj", "esaEmpno.id", emp.getId()))
				info = StringUtil
						.addConcatStr(
								info,
								"\u3001",
								new Object[] { "\u5B58\u5728\u8C03\u85AA\u8BA1\u5212" });
			if (checkRelate("Empsalaryconfig", "id", emp.getId()))
				info = StringUtil
						.addConcatStr(
								info,
								"\u3001",
								new Object[] { "\u5B58\u5728\u85AA\u8D44\u914D\u7F6E" });
			if (checkRelate("Empsalarypay", "espEmpno.id", emp.getId()))
				info = StringUtil
						.addConcatStr(
								info,
								"\u3001",
								new Object[] { "\u5B58\u5728\u85AA\u8D44\u53D1\u653E" });
			int count = 0;
			DetachedCriteria detachedCriteria = DetachedCriteria
					.forClass(com.wyzz.hr.pojo.Empbenefit.class);
			detachedCriteria.createAlias("employee", "employee").add(
					Restrictions.eq("employee.id", emp.getId()));
			count = employeeDAO.findRowCountByCriteria(detachedCriteria);
			if (count > 0)
				info = StringUtil
						.addConcatStr(
								info,
								"\u3001",
								new Object[] { "\u6709\u793E\u4FDD\u8BB0\u5F55\uFF01" });
			if (checkRelate("Leavebalance", "lbEmpNo.id", emp.getId()))
				info = StringUtil.addConcatStr(info, "\u3001",
						new Object[] { "\u6709\u5E74\u5047\u8BB0\u5F55" });
			if (checkRelate("Leaverequest", "lrEmpNo.id", emp.getId()))
				info = StringUtil.addConcatStr(info, "\u3001",
						new Object[] { "\u6709\u8BF7\u5047\u4FE1\u606F" });
			if (checkRelate("Overtimerequest", "orEmpNo.id", emp.getId()))
				info = StringUtil.addConcatStr(info, "\u3001",
						new Object[] { "\u6709\u52A0\u73ED\u4FE1\u606F" });
			if (checkRelate("Attendmonthly", "attmEmpId.id", emp.getId()))
				info = StringUtil
						.addConcatStr(
								info,
								"\u3001",
								new Object[] { "\u4E0E\u6BCF\u6708\u8003\u52E4\u8BB0\u5F55\u5173\u8054" });
			if (checkRelate("Tremployeeplan", "trpTraineeNo.id", emp.getId()))
				info = StringUtil
						.addConcatStr(
								info,
								"\u3001",
								new Object[] { "\u4E0E\u57F9\u8BAD\u8BA1\u5212\u5173\u8054" });
			if (StringUtils.isNotEmpty(info))
				errors.add((new StringBuilder()).append(emp.getEmpName())
						.append("\u4E0D\u80FD\u5220\u9664\uFF01").append(info)
						.append("\n").toString());
			return errors;
		} else {
			return new ArrayList();
		}
	}

	public boolean saveOrUpdateEmpInfo(List empList, List quitList,
			List contractList, List posList) {
		try {
			employeeDAO.saveOrupdate(empList);
			employeeDAO.saveOrupdate(quitList);
			employeeDAO.saveOrupdate(contractList);
			employeeDAO.saveOrupdate(posList);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public String saveCreateEmp(Employee emp, Employee currentEmp,
			String createUser) {
		List errors = insertEmp(emp, currentEmp);
		if (errors.size() > 0)
			return (String) errors.get(0);
		String info = "SUCC";
		if ("true".equals(createUser))
			info = createUser(emp, currentEmp);
		return info;
	}

	public List insertEmp(Employee emp, Employee currentEmp) {
		List errors = checkEmp(emp, "create");
		if (!errors.isEmpty())
			return errors;
		formatEmployeeInfo(emp);
		emp.setEmpDistinctNo(emp.getEmpDistinctNo().trim());
		emp.setEmpName(emp.getEmpName().trim());
		emp.setEmpCreateBy(currentEmp);
		emp.setEmpCreateTime(new Date());
		emp.setEmpLastChangeBy(currentEmp);
		emp.setEmpLastChangeTime(new Date());
		String id = UUID.randomUUID().toString();
		emp.setId(id);
		IPositionBo posBo = (IPositionBo) SpringBeanFactory
				.getBean("positionBo");
		Position pos = posBo.getPosById(emp.getPosition().getId(),
				new String[] { Position.PROP_POSITION_PB_ID });
		String error = posBo.judgePostion(emp.getPosition().getId(), Integer
				.valueOf(1));
		if (!"SUCC".equals(error)) {
			errors.add(error);
			return errors;
		}
		emp.setEmpPbNo(pos.getPositionPbId());
		emp.setEmpMachineNo(findEmployeeMaxMachineNo());
		employeeDAO.saveObject(emp);
		String parentPosId = pos.getPositionParentId() == null ? null : pos
				.getPositionParentId().getId();
		String info = posBo.batchSetEmpPos(parentPosId, pos.getPositionPbId()
				.getId(), new String[] { emp.getId() });
		if (!"SUCC".equals(info))
			errors.add(info);
		IEmpHistOrgBo emphistorgBo = (IEmpHistOrgBo) SpringBeanFactory
				.getBean("empHistOrgBo");
		emphistorgBo.saveEmpHistOrg(emp, emp.getEmpDeptNo(), emp.getEmpPbNo());
		return errors;
	}

	public String createUser(Employee emp, Employee currentEmp) {
		RoleBo roleBo = (RoleBo) SpringBeanFactory.getBean("roleService");
		List defRoles = roleBo.getRoleList(Constants.DEFAULT_USER_AUTHORITY,
				"roleSortId");
		Integer defaultRoleNos[] = new Integer[defRoles.size()];
		for (int i = 0; i < defRoles.size(); i++)
			defaultRoleNos[i] = Integer.valueOf(((Role) defRoles.get(i))
					.getRoleNo());
		String password = RandomStringUtils.random(6, true, true);
		Userinfo user = new Userinfo();
		user.setId(emp.getId());
		user.setUiUsername(emp.getEmpDistinctNo());
		user.setUiPassword(password);
		user.setUiStatus(Integer.valueOf(1));
		user.setUiLevelRestrict(Integer.valueOf(0));
		user.setEmployee(emp);
		UserBo userService = (UserBo) SpringBeanFactory.getBean("userService");
		boolean insertSuccess = userService.addUser(user,
				DEFAULT_USER_AUTHORITY, currentEmp.getId());
		if (!insertSuccess)
			return "\u6DFB\u52A0\u7528\u6237\u5931\u8D25!";
		if (StringUtils.isEmpty(emp.getEmpEmail())) {
			return "SUCC";
		} else {
			Map params = new HashMap();
			params.put("SENDER", currentEmp);
			params.put("APPLIER", emp);
			params.put("USERNAME", emp.getEmpDistinctNo());
			params.put("PASSWORD", password);
			params.put("URL", "configuration/login.jsp");
			IEmailtemplateBO templateBo = (IEmailtemplateBO) SpringBeanFactory
					.getBean("emailtemplateBO");
			Emailtemplate template = templateBo.getEmailTemplateByNo("NewUser");
			IEmailsendBO emailsendBo = (IEmailsendBO) SpringBeanFactory
					.getBean("emailsendBO");
			Emailsend send = emailsendBo.getEmailUser(params, template);
			List esList = new ArrayList();
			esList.add(send);
			emailsendBo.sendEmailsMain(esList);
			return "SUCC";
		}
	}

	private void formatEmployeeInfo(Employee emp) {
		if (emp.getConfig() != null
				&& StringUtils.isEmpty(emp.getConfig().getId()))
			emp.setConfig(null);
		if (emp.getEmpBenefitType() != null
				&& StringUtils.isEmpty(emp.getEmpBenefitType().getId()))
			emp.setEmpBenefitType(null);
		if (emp.getBenefit() != null
				&& StringUtils.isEmpty(emp.getBenefit().getEbfId()))
			emp.setBenefit(null);
		if (emp.getContract() != null
				&& StringUtils.isEmpty(emp.getContract().getEctId()))
			emp.setContract(null);
		if (emp.getQuit() != null
				&& StringUtils.isEmpty(emp.getQuit().getEqId()))
			emp.setQuit(null);
		if (StringUtils.isEmpty(emp.getEmpFname()))
			emp.setEmpFname(null);
		if (StringUtils.isEmpty(emp.getEmpMname()))
			emp.setEmpMname(null);
		if (StringUtils.isEmpty(emp.getEmpLname()))
			emp.setEmpLname(null);
		if (StringUtils.isEmpty(emp.getEmpBlood()))
			emp.setEmpBlood(null);
		if (StringUtils.isEmpty(emp.getEmpPolitics()))
			emp.setEmpPolitics(null);
		if (StringUtils.isEmpty(emp.getEmpDiploma()))
			emp.setEmpDiploma(null);
		if (StringUtils.isEmpty(emp.getEmpSchool()))
			emp.setEmpSchool(null);
		if (StringUtils.isEmpty(emp.getEmpSpeciality()))
			emp.setEmpSpeciality(null);
		if (StringUtils.isEmpty(emp.getEmpCityNo()))
			emp.setEmpCityNo(null);
		if (StringUtils.isEmpty(emp.getEmpNation()))
			emp.setEmpNation(null);
		if (StringUtils.isEmpty(emp.getEmpResidenceLoc()))
			emp.setEmpResidenceLoc(null);
		if (StringUtils.isEmpty(emp.getEmpProfileLoc()))
			emp.setEmpProfileLoc(null);
		if (StringUtils.isEmpty(emp.getEmpHomePhone()))
			emp.setEmpHomePhone(null);
		if (StringUtils.isEmpty(emp.getEmpMobile()))
			emp.setEmpMobile(null);
		if (StringUtils.isEmpty(emp.getEmpCurrAddr()))
			emp.setEmpCurrAddr(null);
		if (StringUtils.isEmpty(emp.getEmpCurrZip()))
			emp.setEmpCurrZip(null);
		if (StringUtils.isEmpty(emp.getEmpHomeAddr()))
			emp.setEmpHomeAddr(null);
		if (StringUtils.isEmpty(emp.getEmpHomeZip()))
			emp.setEmpHomeZip(null);
		if (StringUtils.isEmpty(emp.getEmpEmail()))
			emp.setEmpEmail(null);
		if (StringUtils.isEmpty(emp.getEmpMsn()))
			emp.setEmpMsn(null);
		if (StringUtils.isEmpty(emp.getEmpWorkPhone()))
			emp.setEmpWorkPhone(null);
		if (StringUtils.isEmpty(emp.getEmpImage()))
			emp.setEmpImage(null);
		if (StringUtils.isEmpty(emp.getEmpUrgentContact()))
			emp.setEmpUrgentContact(null);
		if (StringUtils.isEmpty(emp.getEmpUrgentConMethod()))
			emp.setEmpUrgentConMethod(null);
		if (StringUtils.isEmpty(emp.getEmpComments()))
			emp.setEmpComments(null);
		if (StringUtils.isEmpty(emp.getEmpShiftNo()))
			emp.setEmpShiftNo(null);
	}

	public Employee loadEmp(Object id, String fetch[]) {
		return (Employee) employeeDAO.loadObject(Employee.class, id, fetch,
				new boolean[] { false });
	}

	public List loadEmp(String ids[], String fetch[]) {
		DetachedCriteria dc = DetachedCriteria.forClass(Employee.class);
		if (fetch != null) {
			String arr$[] = fetch;
			int len$ = arr$.length;
			for (int i$ = 0; i$ < len$; i$++) {
				String str = arr$[i$];
				dc.setFetchMode(str, FetchMode.JOIN);
			}

		}
		dc.add(Restrictions.in(Employee.PROP_ID, ids));
		List result = employeeDAO.findByCriteria(dc);
		if (result.isEmpty())
			return null;
		else
			return result;
	}

	public List batchUpdateOrDel(Employee emp, String operate, String empNo) {
		List errors = new ArrayList();
		if (emp.getIds() == null || emp.getIds().length() == 0)
			return errors;
		String changIds[] = emp.getIds().split(",");
		Employee temp = null;
		if ("update".equalsIgnoreCase(operate)) {
			for (int len = 0; len < changIds.length; len++) {
				if (changIds[len] == null || changIds[len].length() < 1
						|| "0".equals(changIds[len].trim()))
					continue;
				String tempArray[] = changIds[len].trim().split("&");
				temp = (Employee) employeeDAO.loadObject(
						com.wyzz.hr.pojo.Employee.class, tempArray[0], null,
						new boolean[0]);
				if (temp == null || temp.getId() == null)
					continue;
				List err = checkEmp(temp, "update");
				if (err == null || err.size() < 1) {
					if (emp.getDeptNo() != null && emp.getDeptNo().length() > 1)
						temp.setEmpDeptNo(new Department(emp.getDeptNo()));
					if (emp.getLocationNo() != null
							&& emp.getLocationNo().trim().length() > 0)
						temp.setEmpLocationNo(new Location(emp.getLocationNo()
								.trim()));
					if (emp.getTypeNo() != null
							&& emp.getTypeNo().trim().length() > 0)
						temp.setEmpType(new Emptype(emp.getTypeNo().trim()));
					if (emp.getEmpProfileLoc() != null
							&& emp.getEmpProfileLoc().trim().length() > 0)
						temp.setEmpProfileLoc(emp.getEmpProfileLoc().trim());
					if (emp.getEmpShiftType() != null
							&& !emp.getEmpShiftType().equals(new Integer(0)))
						if (emp.getEmpShiftType().equals(Integer.valueOf(1)))
							temp.setEmpShiftType(Integer.valueOf(0));
						else
							temp.setEmpShiftType(emp.getEmpShiftType());
					temp.setEmpLastChangeBy(new Employee(empNo));
					temp.setEmpLastChangeTime(new Date());
					employeeDAO.updateObject(temp);
				} else {
					errors.addAll(err);
				}
			}

		}
		if ("delete".equalsIgnoreCase(operate)) {
			for (int len = 0; len < changIds.length; len++) {
				if (changIds[len] == null || changIds[len].length() < 1
						|| "0".equals(changIds[len].trim()))
					continue;
				String tempArray[] = changIds[len].trim().split("&");
				temp = (Employee) employeeDAO.loadObject(
						com.wyzz.hr.pojo.Employee.class, tempArray[0], null,
						new boolean[0]);
				if (temp != null && temp.getId() != null) {
					List tempError = deleteEmp(temp);
					errors.addAll(tempError);
				}
			}

		}
		return errors;
	}

	public List searchAndExportEmp(DetachedCriteria dc, Pager page,
			String searchOrExport) {
		if (page == null || "export".equals(searchOrExport)) {
			return employeeDAO.findByCriteria(dc);
		} else {
			page.splitPage(dc);
			return employeeDAO.findByCriteria(dc, page.getPageSize(), page
					.getCurrentPage());
		}
	}

	public List updateEmpByempInfo(Employee emp, String empNo) {
		List errors = checkEmp(emp, "update");
		if (!errors.isEmpty())
			return errors;
		formatEmployeeInfo(emp);
		emp.setEmpLastChangeBy(new Employee(empNo));
		emp.setEmpLastChangeTime(new Date());
		IPositionBo posBo = (IPositionBo) SpringBeanFactory
				.getBean("positionBo");
		Position pos = posBo.getPosById(emp.getPosition().getId(),
				new String[] { Position.PROP_POSITION_PB_ID });
		Employee empInDB = posBo.getEmpWithPos(emp.getId(), new String[0]);
		if (empInDB == null)
			empInDB = loadEmp(emp.getId(), null);
		if (empInDB.getPosition() == null
				|| !empInDB.getPosition().getId().equals(pos.getId())) {
			if (empInDB.getEmpStatus().intValue() == 1) {
				String info = posBo.judgePostion(pos.getId(), Integer
						.valueOf(1));
				if (!"SUCC".equals(info)) {
					errors.add(info);
					return errors;
				}
				String parentPosId = pos.getPositionParentId() == null ? null
						: pos.getPositionParentId().getId();
				String error = posBo.batchSetEmpPos(parentPosId, pos
						.getPositionPbId().getId(),
						new String[] { emp.getId() });
				if (!"SUCC".equals(error)) {
					errors.add(info);
					return errors;
				}
			}
			IEmpHistOrgBo emphistorgBo = (IEmpHistOrgBo) SpringBeanFactory
					.getBean("empHistOrgBo");
			emphistorgBo.saveLatestEmpHistOrg(empInDB, pos.getPositionPbId()
					.getPbDeptId(), pos.getPositionPbId());
		}
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat dateformat2 = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String hql = (new StringBuilder())
				.append("update Employee set empDistinctNo='")
				.append(emp.getEmpDistinctNo().trim())
				.append("' , empName='")
				.append(emp.getEmpName().trim())
				.append("' , empFname=")
				.append(
						emp.getEmpFname() != null ? (new StringBuilder())
								.append("'").append(emp.getEmpFname().trim())
								.append("'").toString() : "null")
				.append(" , empMname=")
				.append(
						emp.getEmpMname() != null ? (new StringBuilder())
								.append("'").append(emp.getEmpMname().trim())
								.append("'").toString() : "null")
				.append(" , empLname=")
				.append(
						emp.getEmpLname() != null ? (new StringBuilder())
								.append("'").append(emp.getEmpLname().trim())
								.append("'").toString() : "null")
				.append(" , empBirthDate='")
				.append(dateformat.format(emp.getEmpBirthDate()))
				.append("' , empMarital=")
				.append(emp.getEmpMarital())
				.append(" , empGender=")
				.append(emp.getEmpGender())
				.append(" , empBlood=")
				.append(
						emp.getEmpBlood() != null ? (new StringBuilder())
								.append("'").append(emp.getEmpBlood().trim())
								.append("'").toString() : "null")
				.append(" , empPolitics=")
				.append(
						emp.getEmpPolitics() != null ? (new StringBuilder())
								.append("'")
								.append(emp.getEmpPolitics().trim())
								.append("'").toString() : "null")
				.append(" , empDiploma=")
				.append(
						emp.getEmpDiploma() != null ? (new StringBuilder())
								.append("'").append(emp.getEmpDiploma().trim())
								.append("'").toString() : "null")
				.append(" , empSchool=")
				.append(
						emp.getEmpSchool() != null ? (new StringBuilder())
								.append("'").append(emp.getEmpSchool().trim())
								.append("'").toString() : "null")
				.append(" , empSpeciality=")
				.append(
						emp.getEmpSpeciality() != null ? (new StringBuilder())
								.append("'").append(
										emp.getEmpSpeciality().trim()).append(
										"'").toString() : "null")
				.append(" , empCityNo=")
				.append(
						emp.getEmpCityNo() != null ? (new StringBuilder())
								.append("'").append(emp.getEmpCityNo().trim())
								.append("'").toString() : "null")
				.append(" , empNation=")
				.append(
						emp.getEmpNation() != null ? (new StringBuilder())
								.append("'").append(emp.getEmpNation().trim())
								.append("'").toString() : "null")
				.append(" , empResidenceLoc=")
				.append(
						emp.getEmpResidenceLoc() != null ? (new StringBuilder())
								.append("'").append(
										emp.getEmpResidenceLoc().trim())
								.append("'").toString()
								: "null")
				.append(" , empProfileLoc=")
				.append(
						emp.getEmpProfileLoc() != null ? (new StringBuilder())
								.append("'").append(
										emp.getEmpProfileLoc().trim()).append(
										"'").toString() : "null")
				.append(" , empIdentificationType=")
				.append(emp.getEmpIdentificationType())
				.append(" , empIdentificationNo='")
				.append(emp.getEmpIdentificationNo().trim())
				.append("' , empBenefitType.id=")
				.append(
						emp.getEmpBenefitType() != null ? (new StringBuilder())
								.append("'").append(
										emp.getEmpBenefitType().getId())
								.append("'").toString() : "null")
				.append(" , empHomePhone=")
				.append(
						emp.getEmpHomePhone() != null ? (new StringBuilder())
								.append("'").append(
										emp.getEmpHomePhone().trim()).append(
										"'").toString() : "null")
				.append(" , empMobile=")
				.append(
						emp.getEmpMobile() != null ? (new StringBuilder())
								.append("'").append(emp.getEmpMobile().trim())
								.append("'").toString() : "null")
				.append(" , empCurrAddr=")
				.append(
						emp.getEmpCurrAddr() != null ? (new StringBuilder())
								.append("'")
								.append(emp.getEmpCurrAddr().trim())
								.append("'").toString() : "null")
				.append(" , empCurrZip=")
				.append(
						emp.getEmpCurrZip() != null ? (new StringBuilder())
								.append("'").append(emp.getEmpCurrZip().trim())
								.append("'").toString() : "null")
				.append(" , empHomeAddr=")
				.append(
						emp.getEmpHomeAddr() != null ? (new StringBuilder())
								.append("'")
								.append(emp.getEmpHomeAddr().trim())
								.append("'").toString() : "null")
				.append(" , empHomeZip=")
				.append(
						emp.getEmpHomeZip() != null ? (new StringBuilder())
								.append("'").append(emp.getEmpHomeZip().trim())
								.append("'").toString() : "null")
				.append(" , empEmail=")
				.append(
						emp.getEmpEmail() != null ? (new StringBuilder())
								.append("'").append(emp.getEmpEmail().trim())
								.append("'").toString() : "null")
				.append(" , empMsn=")
				.append(
						emp.getEmpMsn() != null ? (new StringBuilder()).append(
								"'").append(emp.getEmpMsn().trim()).append("'")
								.toString() : "null")
				.append(" , empWorkPhone=")
				.append(
						emp.getEmpWorkPhone() != null ? (new StringBuilder())
								.append("'").append(
										emp.getEmpWorkPhone().trim()).append(
										"'").toString() : "null")
				.append(" , empShiftType=")
				.append(
						emp.getEmpShiftType() != null ? ((Object) (emp
								.getEmpShiftType())) : "null")
				.append(" , empShiftNo=")
				.append(
						emp.getEmpShiftNo() != null ? (new StringBuilder())
								.append("'").append(emp.getEmpShiftNo().trim())
								.append("'").toString() : "null")
				.append(" , empType.id='")
				.append(emp.getEmpType().getId())
				.append("' , empImage=")
				.append(
						emp.getEmpImage() != null ? (new StringBuilder())
								.append("'").append(emp.getEmpImage().trim())
								.append("'").toString() : "null")
				.append(" , empWorkDate=")
				.append(
						emp.getEmpWorkDate() != null ? (new StringBuilder())
								.append("'")
								.append(dateformat.format(emp.getEmpWorkDate()))
								.append("'").toString()
								: "null")
				.append(" , empJoinDate='")
				.append(dateformat.format(emp.getEmpJoinDate()))
				.append("' , empConfirmDate=")
				.append(
						emp.getEmpConfirmDate() != null ? (new StringBuilder())
								.append("'").append(
										dateformat.format(emp
												.getEmpConfirmDate())).append(
										"'").toString() : "null")
				.append(" , empLocationNo.id='")
				.append(emp.getEmpLocationNo().getId())
				.append("' , empDeptNo.id='")
				.append(emp.getEmpDeptNo().getId())
				.append("' , empPbNo.id='")
				.append(pos.getPositionPbId().getId())
				.append("' , empUrgentContact=")
				.append(
						emp.getEmpUrgentContact() != null ? (new StringBuilder())
								.append("'").append(
										emp.getEmpUrgentContact().trim())
								.append("'").toString()
								: "null")
				.append(" , empUrgentConMethod=")
				.append(
						emp.getEmpUrgentConMethod() != null ? (new StringBuilder())
								.append("'").append(
										emp.getEmpUrgentConMethod().trim())
								.append("'").toString()
								: "null")
				.append(" , empComments=")
				.append(
						emp.getEmpComments() != null ? (new StringBuilder())
								.append("'")
								.append(emp.getEmpComments().trim())
								.append("'").toString() : "null")
				.append(" , empLastChangeBy.id=")
				.append(
						emp.getEmpLastChangeBy() != null ? (new StringBuilder())
								.append("'").append(
										emp.getEmpLastChangeBy().getId())
								.append("'").toString()
								: "null").append(" , empLastChangeTime='")
				.append(dateformat2.format(new Date())).append("' where id='")
				.append(emp.getId()).append("'").toString();
		employeeDAO.updateHqlQuery(hql);
		return errors;
	}

	public void updateEmp(String updateEmpId, String currEmpId,
			String contractId) {
		String hql = (new StringBuilder()).append(
				"update Employee set contract.ectId='").append(contractId)
				.append("',empLastChangeBy.id='").append(currEmpId).append(
						"',empLastChangeTime='").append(
						new java.sql.Date((new Date()).getTime())).append(
						"' where id='").append(updateEmpId).append("'")
				.toString();
		employeeDAO.exeHql(hql);
	}

	public List searchEmpContract(String empNos[]) {
		if (empNos == null || empNos.length == 0) {
			return new ArrayList();
		} else {
			DetachedCriteria detachedCriteria = DetachedCriteria
					.forClass(com.wyzz.hr.pojo.Employee.class);
			detachedCriteria.setFetchMode(Employee.PROP_EMP_CONTRACT,
					FetchMode.JOIN);
			detachedCriteria.add(Restrictions.in(Employee.PROP_ID, empNos));
			List result = employeeDAO.findByCriteria(detachedCriteria);
			return result;
		}
	}

	public List searchEmpArray(String empNos[]) {
		if (empNos == null || empNos.length == 0) {
			return new ArrayList();
		} else {
			DetachedCriteria detachedCriteria = DetachedCriteria
					.forClass(com.wyzz.hr.pojo.Employee.class);
			detachedCriteria.add(Restrictions.in(Employee.PROP_ID, empNos));
			List result = employeeDAO.findByCriteria(detachedCriteria);
			return result;
		}
	}

	public IStatusDAO getStatusDAO() {
		return statusDAO;
	}

	public void setStatusDAO(IStatusDAO statusDAO) {
		this.statusDAO = statusDAO;
	}

	public List getAllRootNodes() {
		List empList = employeeDAO
				.exeHqlList("select id, empName, empType.id, empDistinctNo from Employee  where empStatus=1 and (empSupNo is null or empSupNo.id=id) order by empName asc");
		return empList;
	}

	public List findDirectEmps(String id) {
		String hql = (new StringBuilder())
				.append(
						"select distinct positionEmpNo.id from Position pos where pos.positionParentId in ( select id from Position pos1 where pos1.positionEmpNo.id ='")
				.append(id).append("')").toString();
		List empIdList = employeeDAO.exeHqlList(hql);
		if (empIdList == null || empIdList.size() == 0) {
			return null;
		} else {
			DetachedCriteria dc = DetachedCriteria
					.forClass(com.wyzz.hr.pojo.Employee.class);
			dc.setFetchMode(Employee.PROP_EMP_PB_NO, FetchMode.JOIN);
			dc.add(Restrictions.in(Employee.PROP_ID, empIdList));
			dc.addOrder(Order.asc(Employee.PROP_EMP_DISTINCT_NO));
			return employeeDAO.findByCriteria(dc);
		}
	}

	public int countAllEmpNumbers(String id) {
		if (id == null || id.trim().length() < 1)
			return 0;
		DetachedCriteria dc = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Position.class);
		dc.add(Restrictions.isNotNull(Position.PROP_POSITION_EMP_NO));
		List posList = employeeDAO.findByCriteria(dc);
		List selfPosList = new ArrayList();
		for (int i = 0; posList != null && i < posList.size(); i++) {
			Position pos = (Position) posList.get(i);
			if (pos.getPositionEmpNo() != null
					&& id.equals(pos.getPositionEmpNo().getId()))
				selfPosList.add(pos);
		}

		if (selfPosList.size() == 0)
			return 0;
		List subPosList = new ArrayList();
		for (int i = 0; i < selfPosList.size(); i++) {
			Position selfPos = (Position) selfPosList.get(i);
			List tempSubPosList = new ArrayList();
			tempSubPosList.add(selfPos);
			label0: for (int j = 0; j < tempSubPosList.size(); j++) {
				Position pos = (Position) tempSubPosList.get(j);
				Iterator iter = posList.iterator();
				do {
					if (!iter.hasNext())
						continue label0;
					Position posTemp = (Position) iter.next();
					if (pos != null
							&& posTemp != null
							&& posTemp.getPositionParentId() != null
							&& pos.getId().equals(
									posTemp.getPositionParentId().getId()))
						tempSubPosList.add(posTemp);
				} while (true);
			}

			tempSubPosList.remove(0);
			subPosList.addAll(tempSubPosList);
		}

		return subPosList.size();
	}

	public List findNouserEmps() {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Employee.class);
		detachedCriteria.add(Restrictions.eq("empStatus", new Integer(1)));
		detachedCriteria
				.add(Restrictions
						.sqlRestriction("emp_no not in (select ui_emp_no from userinfo) order by emp_name"));
		return employeeDAO.findByCriteria(detachedCriteria);
	}

	public List loadAll() {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Employee.class);
		detachedCriteria.addOrder(Order.asc(Employee.PROP_EMP_NAME));
		return employeeDAO.findByCriteria(detachedCriteria);
	}

	public List loadAllInService() {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Employee.class);
		detachedCriteria.add(Restrictions.eq("empStatus", new Integer(1)));
		detachedCriteria.addOrder(Order.asc(Employee.PROP_EMP_NAME));
		return employeeDAO.findByCriteria(detachedCriteria);
	}

	public List getPbActiveEmpNos(String pbId) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Employee.class);
		detachedCriteria.add(Restrictions.eq((new StringBuilder()).append(
				Employee.PROP_EMP_PB_NO).append(".").append(
				PositionBase.PROP_ID).toString(), pbId));
		detachedCriteria.add(Restrictions.eq("empStatus", new Integer(1)));
		detachedCriteria.setProjection(Projections
				.property(Employee.PROP_EMP_NAME));
		return employeeDAO.findByCriteria(detachedCriteria);
	}

	public boolean checkEmpInCharge(Employee employer, Employee employee) {
		if (employer == null || employee == null)
			return false;
		if (employer.getId().equals(employee.getId()))
			return true;
		IPositionBo posBo = (IPositionBo) SpringBeanFactory
				.getBean("positionBo");
		Position employerPos = posBo.getPosByEmpNo(employer.getId(),
				new String[] { Position.PROP_POSITION_PB_ID });
		List subPosList = posBo.getAllSubPositions(null,
				new String[] { employerPos.getId() });
		for (int i = 0; subPosList != null && i < subPosList.size(); i++) {
			Position pos = (Position) subPosList.get(i);
			if (pos.getPositionEmpNo() != null
					&& employee.getId().equals(pos.getPositionEmpNo().getId()))
				return true;
		}

		return false;
	}

	public List loadEmpDetails(String ids[]) {
		if (null == ids || ids.length == 0) {
			return new ArrayList();
		} else {
			DetachedCriteria detachedCriteria = DetachedCriteria
					.forClass(com.wyzz.hr.pojo.Employee.class);
			detachedCriteria.add(Restrictions.in("id", ids));
			return employeeDAO.findByCriteria(detachedCriteria);
		}
	}

	public List batchTransfer(Emptransfer transfer, String ids[], String empNo,
			Position newPosition) {
		List errors = new ArrayList();
		List list = loadEmpDetails(ids);
		int count = 0;
		if (transfer.getEftTransferType().equals("4")) {
			for (int i = 0; i < list.size(); i++) {
				Employee emp = (Employee) list.get(i);
				if (emp.getEmpType().getId().equals(
						transfer.getEftNewEmpType().getId())) {
					errors.add(StringUtil.message(msgIsREG, new Object[] { emp
							.getEmpName() }));
					return errors;
				}
				if (newPosition != null
						&& emp.getEmpPbNo() != null
						&& !emp.getEmpPbNo().getId().equals(
								newPosition.getPositionPbId().getId()))
					count++;
			}

		} else {
			if (newPosition == null) {
				errors.add(msgPbNull);
				return errors;
			}
			for (int i = 0; i < list.size(); i++) {
				Employee emp = (Employee) list.get(i);
				if (emp.getEmpPbNo() != null
						&& emp.getEmpPbNo().getId().equals(
								newPosition.getPositionPbId().getId())) {
					errors.add(StringUtil.message(msgPbNoChange,
							new Object[] { emp.getEmpName() }));
					return errors;
				}
			}

			count = ids.length;
		}
		if (count != 0) {
			IPositionBo posBo = (IPositionBo) SpringBeanFactory
					.getBean("positionBo");
			String info = posBo.judgePostion(newPosition.getId(), Integer
					.valueOf(count));
			if (!"SUCC".equals(info)) {
				errors.add(info);
				return errors;
			}
		}
		if (newPosition != null) {
			IPositionBo posBo = (IPositionBo) SpringBeanFactory
					.getBean("positionBo");
			String parentPosId = newPosition.getPositionParentId() == null ? null
					: newPosition.getPositionParentId().getId();
			String info = posBo.batchSetEmpPos(parentPosId, newPosition
					.getPositionPbId().getId(), ids);
			if (!"SUCC".equals(info)) {
				errors.add(info);
				return errors;
			}
		}
		Department newDept = null;
		if (transfer.getEftNewDeptNo() != null
				&& StringUtils.isNotEmpty(transfer.getEftNewDeptNo().getId()))
			newDept = (Department) employeeDAO.loadObject(
					com.wyzz.hr.pojo.Department.class, transfer
							.getEftNewDeptNo().getId(), null, new boolean[0]);
		int size = list.size();
		for (int i = 0; i < size; i++) {
			Employee emp = (Employee) list.get(i);
			String info = saveTransfer(emp, transfer, empNo, newPosition,
					newDept);
			if (!"SUCC".equals(info)) {
				errors.add(info);
				return errors;
			}
		}

		return errors;
	}

	private String saveTransfer(Employee employee, Emptransfer transfer,
			String empNo, Position newPosition, Department newDept) {
		Emptransfer trans = new Emptransfer();
		trans.setEmployee(employee);
		trans.setEftReason(transfer.getEftReason());
		trans.setEftTransferDate(transfer.getEftTransferDate());
		trans.setEftTransferType(transfer.getEftTransferType());
		trans.setEftComments(transfer.getEftComments());
		trans.setEftCreateBy(empNo);
		trans.setEftLastChangeBy(empNo);
		trans.setEftCreateDate(new Date());
		trans.setEftLastChangeTime(new Date());
		trans.setEftOldDeptNo(employee.getEmpDeptNo());
		trans.setEftOldPbId(employee.getEmpPbNo());
		if (newPosition != null) {
			trans.setEftNewDeptNo(newDept);
			trans.setEftNewPbId(newPosition.getPositionPbId());
		}
		if (transfer.getEftTransferType().equals("4")) {
			trans.setEftOldEmpType(employee.getEmpType());
			trans.setEftNewEmpType(transfer.getEftNewEmpType());
			employee.setEmpType(transfer.getEftNewEmpType());
		}
		employeeDAO.saveObject(trans);
		if (newPosition != null
				&& !employee.getEmpPbNo().getId().equals(
						newPosition.getPositionPbId().getId())) {
			IEmpHistOrgBo emphistorgBo = (IEmpHistOrgBo) SpringBeanFactory
					.getBean("empHistOrgBo");
			emphistorgBo.saveEmpHistOrg(employee, newDept, newPosition
					.getPositionPbId());
		}
		if (newPosition != null) {
			employee.setEmpDeptNo(newDept);
			employee.setEmpPbNo(newPosition.getPositionPbId());
		}
		employee.setEmpLastChangeBy(new Employee(empNo));
		employee.setEmpLastChangeTime(new Date());
		employeeDAO.saveOrupdate(employee);
		return "SUCC";
	}

	public Map getEmployeeMap(Collection empIds) {
		if (empIds == null || empIds.isEmpty())
			return new HashMap(0);
		StringBuffer hqlBuffer = new StringBuffer();
		hqlBuffer.append("select id,empName from Employee where");
		for (Iterator it = empIds.iterator(); it.hasNext(); hqlBuffer
				.append("' or")) {
			hqlBuffer.append(" id='");
			hqlBuffer.append((String) it.next());
		}

		String hql = hqlBuffer.toString();
		hql = hql.substring(0, hql.length() - 2);
		List emps = employeeDAO.exeHqlList(hql);
		Map resultMap = new HashMap();
		Object emp[];
		for (Iterator i$ = emps.iterator(); i$.hasNext(); resultMap.put(emp[0]
				.toString(), emp[1].toString()))
			emp = (Object[]) i$.next();

		return resultMap;
	}

	public List getEmpsNeedCard(Integer status, String empNoArray[]) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Employee.class);
		if (status != null && status.intValue() == 1)
			detachedCriteria.add(Restrictions.eq(Employee.PROP_EMP_STATUS,
					Integer.valueOf(1)));
		detachedCriteria.add(Restrictions.or(Restrictions.eq(
				Employee.PROP_EMP_SHIFT_TYPE, Integer.valueOf(2)), Restrictions
				.eq(Employee.PROP_EMP_SHIFT_TYPE, Integer.valueOf(3))));
		if (empNoArray != null && empNoArray.length > 0)
			detachedCriteria.add(Restrictions.in(Employee.PROP_ID, empNoArray));
		List result = employeeDAO.findByCriteria(detachedCriteria);
		if (result.isEmpty())
			return null;
		else
			return result;
	}

	public List findAllActiveEmployees(String year) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Employee.class);
		Date startDate = DateUtil.getYearFirstDay(Integer.parseInt(year));
		Date endDate = DateUtil.getYearEndDay(Integer.parseInt(year));
		detachedCriteria.add(Restrictions.le(Employee.PROP_EMP_JOIN_DATE,
				endDate));
		detachedCriteria.add(Restrictions.or(Restrictions.eq(
				Employee.PROP_EMP_STATUS, Integer.valueOf(1)), Restrictions
				.and(Restrictions.eq(Employee.PROP_EMP_STATUS, Integer
						.valueOf(0)), Restrictions.ge(
						Employee.PROP_EMP_TERMINATE_DATE, startDate))));
		return employeeDAO.findByCriteria(detachedCriteria);
	}

	public synchronized Integer findEmployeeMaxMachineNo() {
		String hql = "select max(empMachineNo) from Employee";
		List maxNoList = employeeDAO.exeHqlList(hql);
		Integer maxID;
		if (maxNoList == null || maxNoList.size() < 1
				|| maxNoList.get(0) == null)
			maxID = Integer.valueOf(1);
		else
			maxID = Integer.valueOf(((Integer) (Integer) maxNoList.get(0))
					.intValue() + 1);
		return maxID;
	}

	public List getEmpSumReport(String startDate, String endDate, String groupBy) {
		List<Date> dateList;
		if (groupBy.equals("0"))
			dateList = DateUtil.getIntervalByMonth(DateUtil.parseDateByFormat(
					startDate, "yyyy-MM-dd"), DateUtil.parseDateByFormat(
					endDate, "yyyy-MM-dd"));
		else
			dateList = DateUtil.getIntervalByYear(DateUtil.parseDateByFormat(
					startDate, "yyyy-MM-dd"), DateUtil.parseDateByFormat(
					endDate, "yyyy-MM-dd"));
		if (dateList == null || dateList.size() < 1)
			return null;
		List empList = loadAll();
		System.out.println(empList.size() + "fffffffffffffff");
		List reportList = new ArrayList();
		if (groupBy.equals("0") && dateList.size() > 12)
			dateList = dateList.subList(0, 12);
		Map dateSumMap = getEmpSumForReport(dateList, groupBy, empList);
		for (Date date : dateList) {
			String name;
			if (groupBy.equals("0"))
				name = DateUtil.getYear(date) + "/" + DateUtil.getMonth(date);
			else {
				name = DateUtil.getYear(date) + "";
			}
			EmpSumReport reportObj = new EmpSumReport();
			reportObj.setName(name);
			reportObj.setTotal(((Integer) dateSumMap.get(date)).intValue());
			reportList.add(reportObj);
		}
		return reportList;
	}

	public List findDimissionEmpInStartAndEnd(String startDate, String endDate,
			String groupBy) {
		List dateList;
		if (groupBy.equals("0"))
			dateList = DateUtil.getIntervalByMonth(DateUtil.parseDateByFormat(
					startDate, "yyyy-MM-dd"), DateUtil.parseDateByFormat(
					endDate, "yyyy-MM-dd"));
		else
			dateList = DateUtil.getIntervalByYear(DateUtil.parseDateByFormat(
					startDate, "yyyy-MM-dd"), DateUtil.parseDateByFormat(
					endDate, "yyyy-MM-dd"));
		if (dateList == null || dateList.size() < 1)
			return null;
		List empList = findAllDimissionEmployees();
		List reportList = new ArrayList();
		if (groupBy.equals("0") && dateList.size() > 12)
			dateList = dateList.subList(0, 12);
		Map dateSumMap = getEmpDimSumForReport(dateList, groupBy, empList);
		EmpSumReport reportObj;
		for (Iterator i$ = dateList.iterator(); i$.hasNext(); reportList
				.add(reportObj)) {
			Date date = (Date) i$.next();
			String name;
			if (groupBy.equals("0"))
				name = (new StringBuilder()).append(DateUtil.getYear(date))
						.append("/").append(DateUtil.getMonth(date)).toString();
			else
				name = (new StringBuilder()).append(DateUtil.getYear(date))
						.append("").toString();
			reportObj = new EmpSumReport();
			reportObj.setName(name);
			reportObj.setTotal(((Integer) dateSumMap.get(date)).intValue());
		}

		return reportList;
	}

	private Map getEmpSumForReport(List<Date> dateList, String groupBy,
			List<Employee> empList) {
		Map dateSumMap = new HashMap();
		for (Date date : dateList) {
			Date borderDate;
			if (groupBy.equals("0"))
				borderDate = DateUtil.getYearMonthEndDay(
						DateUtil.getYear(date), DateUtil.getMonth(date));
			else {
				borderDate = DateUtil.getYearMonthFirstDay(DateUtil
						.getYear(date), DateUtil.getMonth(date));
			}
			int sum = 0;
			for (Employee emp : empList) {
				if ((emp.getEmpJoinDate().compareTo(borderDate) <= 0)
						&& (((emp.getEmpTerminateDate() == null) || (emp
								.getEmpTerminateDate().compareTo(borderDate) > 0)))) {
					++sum;
				}
			}
			dateSumMap.put(date, Integer.valueOf(sum));
		}
		return dateSumMap;
	}

	private Map getEmpNewForReport(List dateList, String groupBy, List empList) {
		Map dateSumMap = new HashMap();
		Date date;
		int sum;
		label0: for (Iterator i$ = dateList.iterator(); i$.hasNext(); dateSumMap
				.put(date, Integer.valueOf(sum))) {
			date = (Date) i$.next();
			Date upperDate;
			Date lowDate;
			if (groupBy.equals("0")) {
				upperDate = DateUtil.getYearMonthFirstDay(DateUtil
						.getYear(date), DateUtil.getMonth(date));
				lowDate = DateUtil.getYearMonthEndDay(DateUtil.getYear(date),
						DateUtil.getMonth(date));
			} else {
				upperDate = DateUtil.getYearMonthFirstDay(DateUtil
						.getYear(date), DateUtil.getMonth(date));
				lowDate = DateUtil.getYearMonthEndDay(DateUtil.getYear(date),
						11);
			}
			sum = 0;
			i$ = empList.iterator();
			do {
				if (!i$.hasNext())
					continue label0;
				Employee emp = (Employee) i$.next();
				if (emp.getEmpJoinDate().compareTo(upperDate) >= 0
						&& emp.getEmpJoinDate().compareTo(lowDate) <= 0)
					sum++;
			} while (true);
		}

		return dateSumMap;
	}

	private Map getEmpDimSumForReport(List dateList, String groupBy,
			List empList) {
		Map dateSumMap = new HashMap();
		Date date;
		int sum;
		label0: for (Iterator i$ = dateList.iterator(); i$.hasNext(); dateSumMap
				.put(date, Integer.valueOf(sum))) {
			date = (Date) i$.next();
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			Date borderDate;
			Date firstDate;
			if (groupBy.equals("0")) {
				borderDate = DateUtil.getYearMonthEndDay(
						DateUtil.getYear(date), DateUtil.getMonth(date));
				firstDate = DateUtil.getFirstDayInMonth(cal).getTime();
			} else {
				borderDate = DateUtil.getLastDayInYear(cal).getTime();
				firstDate = DateUtil.getYearMonthFirstDay(DateUtil
						.getYear(date), DateUtil.getMonth(date));
			}
			sum = 0;
			i$ = empList.iterator();
			do {
				if (!i$.hasNext())
					continue label0;
				Employee emp = (Employee) i$.next();
				if (emp.getEmpTerminateDate() != null
						&& emp.getEmpTerminateDate().compareTo(borderDate) <= 0
						&& emp.getEmpTerminateDate().compareTo(firstDate) >= 0)
					sum++;
			} while (true);
		}

		return dateSumMap;
	}

	public List getEmpNewReport(String startDate, String endDate, String groupBy) {
		List dateList;
		if (groupBy.equals("0"))
			dateList = DateUtil.getIntervalByMonth(DateUtil.parseDateByFormat(
					startDate, "yyyy-MM-dd"), DateUtil.parseDateByFormat(
					endDate, "yyyy-MM-dd"));
		else
			dateList = DateUtil.getIntervalByYear(DateUtil.parseDateByFormat(
					startDate, "yyyy-MM-dd"), DateUtil.parseDateByFormat(
					endDate, "yyyy-MM-dd"));
		if (dateList == null || dateList.size() < 1)
			return null;
		List empList = loadAll();
		List reportList = new ArrayList();
		if (groupBy.equals("0") && dateList.size() > 12)
			dateList = dateList.subList(0, 12);
		Map dateSumMap = getEmpNewForReport(dateList, groupBy, empList);
		EmpSumReport reportObj;
		for (Iterator i$ = dateList.iterator(); i$.hasNext(); reportList
				.add(reportObj)) {
			Date date = (Date) i$.next();
			String name;
			if (groupBy.equals("0"))
				name = (new StringBuilder()).append(DateUtil.getYear(date))
						.append("/").append(DateUtil.getMonth(date)).toString();
			else
				name = (new StringBuilder()).append(DateUtil.getYear(date))
						.append("").toString();
			reportObj = new EmpSumReport();
			reportObj.setName(name);
			reportObj.setTotal(((Integer) dateSumMap.get(date)).intValue());
		}

		return reportList;
	}

	public List getEmpNewRateReport(String startDate, String endDate,
			String groupBy) {
		List dateList;
		if (groupBy.equals("0"))
			dateList = DateUtil.getIntervalByMonth(DateUtil.parseDateByFormat(
					startDate, "yyyy-MM-dd"), DateUtil.parseDateByFormat(
					endDate, "yyyy-MM-dd"));
		else
			dateList = DateUtil.getIntervalByYear(DateUtil.parseDateByFormat(
					startDate, "yyyy-MM-dd"), DateUtil.parseDateByFormat(
					endDate, "yyyy-MM-dd"));
		if (dateList == null || dateList.size() < 1)
			return null;
		List empList = loadAll();
		List reportList = new ArrayList();
		if (groupBy.equals("0") && dateList.size() > 12)
			dateList = dateList.subList(0, 12);
		Map dateSumMap = getEmpSumForReport(dateList, groupBy, empList);
		Map dateNewMap = getEmpNewForReport(dateList, groupBy, empList);
		EmpSumReport reportObj;
		for (Iterator i$ = dateList.iterator(); i$.hasNext(); reportList
				.add(reportObj)) {
			Date date = (Date) i$.next();
			int newSum = ((Integer) dateNewMap.get(date)).intValue();
			int sum = ((Integer) dateSumMap.get(date)).intValue();
			int rate = 0;
			if (sum == 0 && newSum != 0)
				rate = 100;
			if (sum != 0)
				rate = (newSum * 100) / sum;
			String name;
			if (groupBy.equals("0"))
				name = (new StringBuilder()).append(DateUtil.getYear(date))
						.append("/").append(DateUtil.getMonth(date)).toString();
			else
				name = (new StringBuilder()).append(DateUtil.getYear(date))
						.append("").toString();
			reportObj = new EmpSumReport();
			reportObj.setName(name);
			reportObj.setTotal(rate);
		}

		return reportList;
	}

	public List getEmpNetRateReport(String startDate, String endDate,
			String groupBy) {
		List dateList;
		if (groupBy.equals("0"))
			dateList = DateUtil.getIntervalByMonth(DateUtil.parseDateByFormat(
					startDate, "yyyy-MM-dd"), DateUtil.parseDateByFormat(
					endDate, "yyyy-MM-dd"));
		else
			dateList = DateUtil.getIntervalByYear(DateUtil.parseDateByFormat(
					startDate, "yyyy-MM-dd"), DateUtil.parseDateByFormat(
					endDate, "yyyy-MM-dd"));
		if (dateList == null || dateList.size() < 1)
			return null;
		List empList = loadAll();
		List reportList = new ArrayList();
		if (groupBy.equals("0") && dateList.size() > 12)
			dateList = dateList.subList(0, 12);
		Map dateSumMap = getEmpSumForReport(dateList, groupBy, empList);
		Map dateNewMap = getEmpNewForReport(dateList, groupBy, empList);
		Map dateDimMap = getEmpDimSumForReport(dateList, groupBy, empList);
		EmpSumReport reportObj;
		for (Iterator i$ = dateList.iterator(); i$.hasNext(); reportList
				.add(reportObj)) {
			Date date = (Date) i$.next();
			int newNum = ((Integer) dateNewMap.get(date)).intValue();
			int sum = ((Integer) dateSumMap.get(date)).intValue();
			int dimNum = ((Integer) dateDimMap.get(date)).intValue();
			int rate = 0;
			int net = newNum - dimNum;
			if (sum != 0)
				rate = (net * 100) / sum;
			String name;
			if (groupBy.equals("0"))
				name = (new StringBuilder()).append(DateUtil.getYear(date))
						.append("/").append(DateUtil.getMonth(date)).toString();
			else
				name = (new StringBuilder()).append(DateUtil.getYear(date))
						.append("").toString();
			reportObj = new EmpSumReport();
			reportObj.setName(name);
			reportObj.setTotal(rate);
		}

		return reportList;
	}

	public List getEmpDimissionRateReport(String startDate, String endDate,
			String groupBy) {
		List dateList;
		if (groupBy.equals("0"))
			dateList = DateUtil.getIntervalByMonth(DateUtil.parseDateByFormat(
					startDate, "yyyy-MM-dd"), DateUtil.parseDateByFormat(
					endDate, "yyyy-MM-dd"));
		else
			dateList = DateUtil.getIntervalByYear(DateUtil.parseDateByFormat(
					startDate, "yyyy-MM-dd"), DateUtil.parseDateByFormat(
					endDate, "yyyy-MM-dd"));
		if (dateList == null || dateList.size() < 1)
			return null;
		List empList = loadAll();
		List reportList = new ArrayList();
		if (groupBy.equals("0") && dateList.size() > 12)
			dateList = dateList.subList(0, 12);
		Map dateSumMap = getEmpDimSumForReport(dateList, groupBy, empList);
		EmpSumReport reportObj;
		for (Iterator i$ = dateList.iterator(); i$.hasNext(); reportList
				.add(reportObj)) {
			Date date = (Date) i$.next();
			Date borderDate;
			if (groupBy.equals("0"))
				borderDate = DateUtil.getYearMonthEndDay(
						DateUtil.getYear(date), DateUtil.getMonth(date));
			else
				borderDate = DateUtil.getYearMonthFirstDay(DateUtil
						.getYear(date), DateUtil.getMonth(date));
			int newSum = 0;
			i$ = empList.iterator();
			do {
				if (!i$.hasNext())
					break;
				Employee emp = (Employee) i$.next();
				if (emp.getEmpJoinDate().compareTo(borderDate) <= 0
						&& (emp.getEmpTerminateDate() == null || emp
								.getEmpTerminateDate().compareTo(borderDate) > 0))
					newSum++;
			} while (true);
			int rate = 0;
			int sum = ((Integer) dateSumMap.get(date)).intValue();
			if (sum == 0)
				rate = 0;
			else if (sum != 0 && newSum != 0)
				rate = (sum * 100) / newSum;
			String name;
			if (groupBy.equals("0"))
				name = (new StringBuilder()).append(DateUtil.getYear(date))
						.append("/").append(DateUtil.getMonth(date)).toString();
			else
				name = (new StringBuilder()).append(DateUtil.getYear(date))
						.append("").toString();
			reportObj = new EmpSumReport();
			reportObj.setName(name);
			reportObj.setTotal(rate);
		}

		return reportList;
	}

	public List findAllDimissionEmployees() {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Employee.class);
		detachedCriteria.addOrder(Order.asc(Employee.PROP_EMP_NAME));
		detachedCriteria.add(Restrictions
				.isNotNull(Employee.PROP_EMP_TERMINATE_DATE));
		return employeeDAO.findByCriteria(detachedCriteria);
	}

	public List getAllEmpBasicInfo() {
		DetachedCriteria dc = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Employee.class);
		dc.createAlias(Employee.PROP_EMP_DEPT_NO, "empDeptNo", 1);
		dc.createAlias(Employee.PROP_EMP_PB_NO, "empPbNo", 1);
		dc.addOrder(Order.asc(Employee.PROP_EMP_NAME));
		return employeeDAO.findByCriteria(dc);
	}

	private boolean checkRelate(String table, String field, String id) {
		IDepartmentDAO dao = (IDepartmentDAO) SpringBeanFactory
				.getBean("departmentDAO");
		String hql = (new StringBuilder()).append("select count(*) from ")
				.append(table).append(" where ").append(field).append("='")
				.append(id).append("'").toString();
		List list = dao.exeHqlList(hql);
		return list != null && list.get(0) != null
				&& ((Long) (Long) list.get(0)).longValue() > 0L;
	}

	public List getEmpDistinct() {
		String hql = "select empDistinctNo from Employee where empStatus=1";
		return employeeDAO.exeHqlList(hql);
	}

	private String msgIsREG;
	private String msgPbNull;
	private String msgPbNoChange;
	private IEmployeeDAO employeeDAO;
	private IStatusDAO statusDAO;
}
